  package com.example.asus.pictures2;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

  public class MainActivity extends AppCompatActivity {
    private ImageView imgStars;
    private Button btnNext;
    private int[]stars={R.drawable.yi,R.drawable.gong,R.drawable.song,
            R.drawable.dean,R.drawable.nan,R.drawable.gray};
    private int index=0;
    //handler是消息机制
    private Handler handler;
    private final int MSG_CHANGE_STARS=1001;
    //判断是否处于暂停状态
    private Boolean isPause=true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imgStars=findViewById(R.id.imgStar);
        btnNext=findViewById(R.id.btnNext);

        //初始化handler
        handler=new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if(msg.what==MSG_CHANGE_STARS){
                    index=(index+1)%stars.length;
                    imgStars.setImageResource(stars[index]);
                    return true;
                }
                return false;
            }
        });
        //改用线程，自动切换图片
        //Thread子线程，在子线程中不能修改主线程创建的view
        //需使用消息机制，告诉主线程更新
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try{
                        Thread.sleep(2000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    if(!isPause){
                        //消息机制
                        Message message=new Message();
                        message.what=MSG_CHANGE_STARS;
                        handler.sendMessage(message);
                        //打印日志
                        Log.e("MainActivity","send change message");
                    }
                }
            }
        }).start();
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isPause=!isPause;
            }
        });
    }
}
